package com.mitrais.training.yoga;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class Service {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		Connection conn = null;
		Statement stmt = null;
		String url = "jdbc:jtds:sqlserver://localhost:1433/test;instance=YOGA";
		String userName = "sa";
		String password = "sapassword";

		try {
			Class.forName("net.sourceforge.jtds.jdbc.Driver").newInstance();
			conn = DriverManager.getConnection(url, userName, password);
			System.out.println("Successfully connected to SQL Server DB");
		} catch (InstantiationException ie) {
			ie.printStackTrace();
		} catch (IllegalAccessException iae) {
			iae.printStackTrace();
		} catch (ClassNotFoundException cnfe) {
			cnfe.printStackTrace();
		} catch (SQLException sqle) {
			sqle.printStackTrace();
		}

		if (conn != null) {
			try {
				stmt = conn.createStatement();
				System.out.println("Successfully creating statement");
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		if (stmt != null) {
			String sql = "INSERT INTO EMPLOYEE (emp_id,emp_name,emp_salary) VALUES ('1','Mark Zuckerberg','3700000')";
			String sql2 = "SELECT * FROM EMPLOYEE";
			try {
				int flag = stmt.executeUpdate(sql);
				if (flag == 1) {
					System.out
							.println("Successfully insert the employee record");
				}
				System.out.println("Displaying all Employee ...");
				ResultSet rs = stmt.executeQuery(sql2);
				while (rs.next()) {
					System.out.println("Employee ID "
							+ rs.getString("emp_id").trim());
					System.out.println("Employee Name "
							+ rs.getString("emp_name").trim());
					System.out.println("Employee Salary "
							+ rs.getDouble("emp_salary"));
					System.out
							.println("--------------------------------------------------");
				}
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	/*
	 * @return conn to return Connection data. this method is intended to
	 * initialize connection to database
	 */
	public static Connection initConnection() {
		Connection conn = null;
		String url = "jdbc:jtds:sqlserver://localhost:1433/test;instance=YOGA";
		String userName = "sa";
		String password = "sapassword";

		try {
			Class.forName("net.sourceforge.jtds.jdbc.Driver").newInstance();
			conn = DriverManager.getConnection(url, userName, password);
			System.out.println("Successfully connected to SQL Server DB");
		} catch (InstantiationException ie) {
			ie.printStackTrace();
		} catch (IllegalAccessException iae) {
			iae.printStackTrace();
		} catch (ClassNotFoundException cnfe) {
			cnfe.printStackTrace();
		} catch (SQLException sqle) {
			sqle.printStackTrace();
		}
		return conn;
	}
}
